package framework.utils;

public class PaginationUtil {

    public static String PAGE_INDEX_NAME = "pageIndex";
    public static String PAGE_SIZE_NAME = "pageSize";

    public static int getPageIndex() {
        Integer pageIndex = ServletUtil.getInteger(PAGE_INDEX_NAME);
        return resolvePageIndex(pageIndex);
    }

    public static int getPageIndex(int defaultPageIndex) {
        Integer pageIndex = ServletUtil.getInteger(PAGE_INDEX_NAME);
        return resolvePageIndex(pageIndex, defaultPageIndex, Integer.MAX_VALUE);
    }

    public static int getPageIndex(int defaultPageIndex, int maxPageIndex) {
        Integer pageIndex = ServletUtil.getInteger(PAGE_INDEX_NAME);
        return resolvePageIndex(pageIndex, defaultPageIndex, maxPageIndex);
    }

    public static int getPageSize() {
        Integer pageSize = ServletUtil.getInteger(PAGE_SIZE_NAME);
        return resolvePageSize(pageSize);
    }

    public static int getPageSize(int defaultPageSize, int maxPageSize) {
        Integer pageSize = ServletUtil.getInteger(PAGE_SIZE_NAME);
        return resolvePageSize(pageSize, defaultPageSize, maxPageSize);
    }

    public static int resolvePageIndex(Integer pageIndex) {
        return resolvePageIndex(pageIndex, 1, Integer.MAX_VALUE);
    }

    public static int resolvePageIndex(Integer pageIndex, int defaultPageIndex, int maxPageIndex) {
        if (pageIndex == null) {
            return defaultPageIndex;
        }
        if (pageIndex < 1) {
            return defaultPageIndex;
        }
        if (pageIndex > maxPageIndex) {
            return maxPageIndex;
        }
        return pageIndex;
    }

    public static int resolvePageSize(Integer pageSize) {
        return resolvePageSize(pageSize, 10, 100);
    }

    public static int resolvePageSize(Integer pageSize, int defaultPageSize, int maxPageSize) {
        if (pageSize == null) {
            return defaultPageSize;
        }
        if (pageSize < 1) {
            return defaultPageSize;
        }
        if (pageSize > maxPageSize) {
            return maxPageSize;
        }
        return pageSize;
    }

}
